package com.hakim.wfb.platform.controller;

/**
 * Created by walkman on 2017/7/1.
 */

import com.hakim.wfb.customer.result.captcha.CaptchaCheckView;
import com.hakim.wfb.platform.utils.RandomValidateCode;
import com.hakim.wfb.platform.utils.StaticTool;
import com.hkfs.fundamental.api.data.ObjectResultEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

@RestController
@RequestMapping(value = "/captcha")
public class CaptchaController {

    private Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    /**
     * 校验验证码是否一致
     *
     * @param code
     * @param request
     * @return
     */
    @RequestMapping(value = "/check-vcode", method = RequestMethod.GET)
    public ObjectResultEx<CaptchaCheckView> checkVCode(@RequestParam String code, HttpServletRequest request) {
        //change code to lower
        code = code.toLowerCase();
        ObjectResultEx<CaptchaCheckView> resultEx = new ObjectResultEx<>();
        CaptchaCheckView checkView = new CaptchaCheckView();
        String sessionCode = StaticTool.getValidCodeForHttpSession(request);
        if (StringUtils.isBlank(code) || StringUtils.isBlank(sessionCode)) {
            checkView.setPassed(false);
        } else {
            if (code.equalsIgnoreCase(sessionCode)) {
                checkView.setPassed(true);
            } else {
                checkView.setPassed(false);
            }
        }
        resultEx.setDataObject(checkView);
        return resultEx.makeSuccessResult();
    }

    /**
     * 生成验证码
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/gen-vcode", method = RequestMethod.GET)
    public void genVCode(HttpServletRequest request, HttpServletResponse response) {

        response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);
        RandomValidateCode randomValidateCode = new RandomValidateCode();
        try {
            randomValidateCode.getRandomCode(request, response);//输出图片方法
        } catch (Exception e) {
            logger.error("", e);
        }
    }
}

